<template>
  <div>
    <div class="content-item">
      <el-form :model="formData"
               ref="form"
               :label-position="labelPosition"
               label-width="106px"
               :rules="rules">
        <el-form-item label="评比名称："
                      prop="name">
          <el-input v-model="formData.name"
                    style="width: 250px;"
                    :disabled="editable && cloneData.status === 4"
                    placeholder="输入评比名称"
                    size="small"></el-input>
        </el-form-item>
        <el-form-item label="评比类型："
                      prop="rateType">
          <el-select v-model="formData.rateType"
                     :disabled="editable && cloneData.status !== 1"
                     size="small"
                     style="width: 250px;"
                     @change="changeRateType"
                     placeholder="--评比类型--">
            <el-option v-for="item in typies"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="星级评比："
                      v-if="formData.rateType !== 1"
                      prop="starRatingId">
          <el-select v-model="formData.starRatingId"
                     size="small"
                     :disabled="editable && cloneData.status !== 1"
                     style="width: 250px;"
                     @change="changeRateType"
                     placeholder="--星级寝室评比--">
            <el-option v-for="item in starsData"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查工作："
                      v-else
                      prop="checkWorkId">
          <el-select v-model="formData.checkWorkId"
                     size="small"
                     :disabled="editable && cloneData.status !== 1"
                     style="width: 250px;"
                     placeholder="--检查工作项--">
            <el-option v-for="item in checkWork"
                       :key="item.id"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间："
                      prop="startAt">
          <el-date-picker v-model="formData.startAt"
                          :disabled="editable && cloneData.status !== 1"
                          @change="timeChange"
                          size="small"
                          :picker-options="startAt"
                          style="width: 250px;"
                          format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"
                          type="date"
                          placeholder="请选择">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间："
                      prop="endAt">
          <el-date-picker v-model="formData.endAt"
                          @change="timeChange"
                          size="small"
                          :picker-options="endAt"
                          style="width: 250px;"
                          format="yyyy-MM-dd"
                          :disabled="editable && cloneData.status === 4"
                          value-format="yyyy-MM-dd"
                          type="date"
                          placeholder="请选择">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="开展校区："
                      prop="schoolAreas">
          <el-checkbox-group v-model="formData.schoolAreas"
                             :disabled="editable && cloneData.status !== 1">
            <el-checkbox v-for="item in campus"
                         :label="item.id"
                         :key="item.id">{{item.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="当前状态："
                      v-if="editable">
          <span>{{formatRateStatus(cloneData.status)}}</span>
        </el-form-item>
        <el-form-item label="评比介绍："
                      prop="description">
          <div id="rich"></div>
        </el-form-item>
      </el-form>

      <div class="g-mt20">
        <el-button size="small"
                   @click="$router.go(-1)">返回</el-button>
        <el-button size="small"
                   type="primary"
                   @click="submit">保存</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import E from 'wangeditor'
import { listCheckWorkUsingPOST, listPageUsingPOST, addRatingUsingPOST, listSchoolAreaUsingGET, modifyRatingUsingPUT } from '@api/auto'
import { formatTool } from '@/tools/mixin'
import { fileServer } from '@/config'
export default {
  name: '',
  props: {
  },
  mixins: [formatTool],
  components: {},
  data () {
    var validateStarRating = (rule, value, callback) => {
      if (this.formData.rateType !== 1 && !value) {
        return callback(new Error('请选择星级检查'))
      }
      callback()
    }
    var validateCheckWork = (rule, value, callback) => {
      if (this.formData.rateType === 1 && !value) {
        return callback(new Error('请选择检查工作项'))
      }
      callback()
    }
    return {
      // 区分新建和编辑
      editable: false,
      labelPosition: 'left',
      starsData: [],
      checkWork: [],
      cloneData: {},
      formData: {
        name: '',
        rateType: '',
        startAt: '',
        endAt: '',
        description: '',
        starRatingId: '',
        checkWorkId: '',
        generateList: 0,
        schoolAreas: []
      },
      rules: {
        name: [
          { required: true, message: '请输入评比名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在1到20个字符', trigger: 'blur' }
        ],
        rateType: [
          { required: true, message: '请选择评比类型', trigger: 'blur' }
        ],
        startAt: [
          { required: true, message: '请选择开始时间', trigger: 'blur' }
        ],
        endAt: [
          { required: true, message: '请选择结束时间', trigger: 'blur' }
        ],
        schoolAreas: [
          { required: true, message: '请选择开展校区', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '输入评比介绍', trigger: 'blur' }
        ],
        starRatingId: [
          { required: true, validator: validateStarRating, trigger: 'blur' }
        ],
        checkWorkId: [
          { required: true, validator: validateCheckWork, trigger: 'blur' }
        ]
      },
      editor: null,
      schoolAreas: [],
      typies: [
        {
          label: '星级文明寝室',
          value: 1
        },
        {
          label: '校文明寝室',
          value: 2
        },
        {
          label: '校标兵文明寝室',
          value: 3
        }
      ],
      campus: [],
      startAt: {
        disabledDate: time => {
          if (this.formData.endAt) {
            return (
              (time.getTime() > new Date(this.formData.endAt).getTime() - 24 * 60 * 60 * 1000) || (time.getTime() < Date.now() - 24 * 60 * 60 * 1000)
            )
          } else {
            return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
          }
        }
      },
      endAt: {
        disabledDate: time => {
          if (this.formData.startAt) {
            return (
              (time.getTime() < new Date(this.formData.startAt).getTime() - 24 * 60 * 60 * 1000) || (time.getTime() < Date.now() - 24 * 60 * 60 * 1000)
            )
          } else {
            return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
          }
        }
      }
    }
  },
  created () {
    this.$route.query.type === 'edit' ? this.editable = true : this.editable = false
    if (this.editable) {
      this.formBackfill()
    }
  },
  mounted () {
    this.renderRichText()
    this.listSchoolArea()
    this.listCheckWorkUsingPOST()
    this.listPageUsingPOST()
  },
  methods: {
    // 获取已结束的检查工作项
    listCheckWorkUsingPOST () {
      let params = {
        page: 1,
        size: 10000,
        status: 3,
        checkType: 1
      }
      listCheckWorkUsingPOST(params)
        .then(res => {
          this.checkWork = res.data && res.data.list
        })
    },
    timeChange (val) {
      console.log(val, new Date(this.formData.startAt).getTime(), new Date(this.formData.endAt).getTime())
    },
    // 初始化富文本
    renderRichText () {
      this.editor = new E(document.getElementById('rich'))
      this.editor.customConfig.menus = [
        'head', // 标题
        'bold', // 粗体
        'fontSize', // 字号
        'fontName', // 字体
        'italic', // 斜体
        'underline', // 下划线
        'strikeThrough', // 删除线
        'foreColor', // 文字颜色
        'backColor', // 背景颜色
        'link', // 插入链接
        'list', // 列表
        'justify', // 对齐方式
        'quote', // 引用
        'emoticon', // 表情
        'image', // 插入图片
        'table', // 表格
        'undo', // 撤销
        'redo' // 重复
      ]
      this.editor.customConfig.uploadImgServer = fileServer.upload
      // 将图片大小限制为 5M
      this.editor.customConfig.uploadImgMaxSize = 5 * 1024 * 1024
      this.editor.customConfig.uploadImgMaxLength = 5
      this.editor.customConfig.zIndex = 100
      this.editor.customConfig.uploadFileName = 'file'
      this.editor.customConfig.debug = true
      this.editor.customConfig.uploadImgHooks = {
        customInsert: function (insertImg, result, editor) {
          console.log(insertImg, result, editor)
          if (result.success) {
            let url = `${fileServer.download}?filePath=${result.filePath}`
            insertImg(url)
          }
        }
      }
      this.editor.create()
      // 编辑回填富文本
      if (this.editable) {
        if (this.cloneData.status === 4) {
          this.editor.$textElem.attr('contenteditable', false)
        }
        this.editor.txt.html(this.formData.description)
      }
    },
    // 新增/编辑提交
    submit () {
      let html = this.editor.txt.html()
      if (html !== `<p><br></p>`) {
        this.formData.description = html
      } else {
        this.formData.description = ''
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.editable) {
            modifyRatingUsingPUT(this.formData)
              .then(() => {
                this.$message.success('修改成功！')
                this.$router.go(-1)
              })
          } else {
            addRatingUsingPOST(this.formData)
              .then(() => {
                this.$message.success('创建成功！')
                this.$router.go(-1)
              })
          }
        }
      })
    },
    listPageUsingPOST () {
      let params = {
        page: 1,
        size: 10000,
        rateType: 1
      }
      listPageUsingPOST(params)
        .then(res => {
          this.starsData = res.data && res.data.list.filter(item => {
            return item.status !== 1 && item.status !== 2
          })
          console.log(this.starsData, 'this.starsData')
        })
    },
    // 评比类型改变
    changeRateType (type) {
      if (~~type !== 1) {
        this.listPageUsingPOST()
      } else {
        this.listCheckWorkUsingPOST()
      }
    },
    // 查询所有校区
    listSchoolArea () {
      listSchoolAreaUsingGET().then(res => {
        this.campus = res.data
      })
    },
    // 编辑数据回填
    formBackfill () {
      let temp = JSON.parse(sessionStorage.rateContent) || false
      this.cloneData = temp
      this.formData.name = temp.name
      this.formData.rateType = temp.rateType
      this.formData.startAt = this.$moment(temp.startAt).format('YYYY-MM-DD')
      this.formData.endAt = this.$moment(temp.endAt).format('YYYY-MM-DD')
      this.formData.description = temp.description
      this.formData.starRatingId = temp.starRatingId
      this.formData.id = temp.id
      this.schoolAreas = temp.schoolAreas
      this.formData.checkWorkId = temp.checkWorkId
      this.formData.schoolAreas = temp.schoolAreas
    }
  }
}
</script>
<style lang='less' scoped>
#rich {
  width: 700px;
  display: inline-block;
}
</style>
